<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="配餐单位" prop="mealUnit">
        <el-input
          v-model="queryParams.mealUnit"
          placeholder="请输入配餐单位"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="航班号" prop="flightNo">
        <el-input
          v-model="queryParams.flightNo"
          placeholder="请输入航班号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="机型" prop="aircraftType">
        <el-input
          v-model="queryParams.aircraftType"
          placeholder="请输入机型"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="起飞地点" prop="depLoc">
        <el-input
          v-model="queryParams.depLoc"
          placeholder="请输入起飞地点"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="降落地点" prop="arrLoc">
        <el-input
          v-model="queryParams.arrLoc"
          placeholder="请输入降落地点"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="机组餐谱" prop="crewMeal">
        <el-input
          v-model="queryParams.crewMeal"
          placeholder="请输入机组餐谱"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <!-- 新增：批量操作按钮 -->

        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['distm:quarter-plan:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="warning"
          plain
          @click="handleImport"
          v-hasPermi="['distm:quarter-plan:import']"
        >
          <Icon icon="ep:upload" /> 导入
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['distm:quarter-plan:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button type="primary" plain @click="openColumnSetting">
          <Icon icon="ep:setting" class="mr-5px" /> 列设置
        </el-button>
        <el-button
          type="primary"
          plain
          @click="handleBatchOperation"
          :disabled="selectedRowKeys.length === 0"
        >
          <Icon icon="ep:edit" class="mr-5px" />生成今日修改计划
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表：虚拟化表格 -->
  <ContentWrap>
    <div style="height: 62vh">
      <el-auto-resizer>
        <template #default="{ height, width }">
          <el-table-v2
            :columns="tableV2Columns"
            :data="list"
            :width="width"
            :height="height"
            fixed
            :loading="loading"
          />
        </template>
      </el-auto-resizer>
    </div>
  </ContentWrap>

  <!-- 列设置弹窗 -->
  <el-dialog
    title="表格列设置"
    v-model="columnSettingVisible"
    width="800px"
    :close-on-click-modal="false"
  >
    <el-checkbox-group v-model="selectedColumns" class="column-setting-group">
      <el-checkbox
        v-for="column in tableColumns"
        :key="column.prop"
        :label="column.prop"
        style="width: 20%"
      >
        {{ column.label }}
      </el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button @click="columnSettingVisible = false">取消</el-button>
      <el-button type="primary" @click="saveColumnSettings">确定</el-button>
    </template>
  </el-dialog>

  <!-- 新增：批量操作弹窗 -->
  <el-dialog
    title="生成今日修改计划"
    v-model="batchDialogVisible"
    width="500px"
    :close-on-click-modal="false"
  >
    <div class="batch-operation-content">
      <el-form
        ref="batchFormRef"
        :model="batchForm"
        label-width="100px"
        :rules="batchFormRules"
        label-position="right"
      >
        <!-- 直接显示开始时间和结束时间，去掉操作类型 -->
        <el-form-item label="开始时间" prop="beginTime">
          <el-date-picker
            v-model="batchForm.beginTime"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="请选择开始时间"
          />
        </el-form-item>

        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="batchForm.endTime"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="请选择结束时间"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="batchDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmBatchOperation">确定</el-button>
    </template>
  </el-dialog>

  <!-- 表单弹窗 -->
  <QuarterPlanForm ref="formRef" @success="getList" />
  <QuarterPlanImportForm ref="importFormRef" @success="getList" />
</template>

<script lang="tsx" setup>
import { ref, reactive, onMounted, computed, watch, h } from 'vue'
import type { Column } from 'element-plus'
import { ElButton, ElTooltip, ElCheckbox, ElSelect, ElOption, ElForm, ElFormItem } from 'element-plus'
import { dateFormatter ,formatDate} from '@/utils/formatTime'
import download from '@/utils/download'
import { QuarterPlanApi, QuarterPlanVO } from '@/api/distm/quarterplan'
import QuarterPlanForm from './QuarterPlanForm.vue'
import QuarterPlanImportForm from './QuarterPlanImportForm.vue'
import { DICT_TYPE } from '@/utils/dict'
import DictTag from '@/components/DictTag/src/DictTag.vue'

/** 基础配置 */
defineOptions({ name: 'QuarterPlan' })
const message = useMessage()
const { t } = useI18n()

// 状态管理
const loading = ref(true)
const list = ref<QuarterPlanVO[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 5000,
  mealUnit: undefined,
  flightNo: undefined,
  aircraftType: undefined,
  depIata: undefined,
  arrLoc: undefined,
  arrTime: [],
  crewMeal: undefined
})
const queryFormRef = ref()
const exportLoading = ref(false)

// 新增：选择列相关状态
const selectedRowKeys = ref<number[]>([]) // 选中的行ID集合
const batchDialogVisible = ref(false) // 批量操作弹窗
// 修改 batchForm，去掉 operationType
const batchForm = reactive({
  beginTime: '', // 开始时间
  endTime: ''   // 结束时间
})
const batchFormRef = ref()

// 修改 batchFormRules，去掉 operationType 规则
const batchFormRules = ref({
  beginTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (batchForm.beginTime && value) {
          if (new Date(batchForm.beginTime) > new Date(value)) {
            callback(new Error('开始时间不能晚于结束时间'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
})

/** 业务逻辑 */
const getList = async () => {
  loading.value = true
  try {
    const data = await QuarterPlanApi.getQuarterPlanPage(queryParams)
    list.value = data.list || []
    total.value = data.total || 0
    // 清空选择状态
    selectedRowKeys.value = []
  } finally {
    loading.value = false
  }
}

const handleQuery = () => getList()

const resetQuery = () => {
  if (queryFormRef.value) queryFormRef.value.resetFields()
  handleQuery()
}

const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await QuarterPlanApi.deleteQuarterPlan(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await QuarterPlanApi.exportQuarterPlan(queryParams)
    download.excel(data, '配送管理-季度计划.xls')
  } catch {} finally {
    exportLoading.value = false
  }
}

const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

/** 新增：选择列相关方法 */
// 全选/取消全选
const handleSelectAll = () => {
  if (isAllSelected.value) {
    selectedRowKeys.value = []
  } else {
    selectedRowKeys.value = list.value.map(item => item.id).filter(id => id !== undefined) as number[]
  }
}
// 单选
const handleSelect = (id: number) => {
  const index = selectedRowKeys.value.indexOf(id)
  if (index > -1) {
    selectedRowKeys.value.splice(index, 1)
  } else {
    selectedRowKeys.value.push(id)
  }
}
// 判断是否全选
const isAllSelected = computed(() => {
  return selectedRowKeys.value.length > 0 && 
  selectedRowKeys.value.length === list.value.filter(item => item.id !== undefined).length
})

// 打开批量操作弹窗
const handleBatchOperation = () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请先选择要操作的记录')
    return
  }
  batchDialogVisible.value = true
}

// 确认批量操作
const confirmBatchOperation = async () => {
  if (!batchFormRef.value) return;

  try {
    // 关键：正确的校验方式
    await batchFormRef.value.validate();

    // 校验通过，执行后续逻辑
    loading.value = true;
    
    await QuarterPlanApi.createTodayEdit({
      ids: selectedRowKeys.value,
      beginTime: batchForm.beginTime,
      endTime: batchForm.endTime
    });
    
    message.success('生成今日修改计划成功');
    batchDialogVisible.value = false;
    await getList();

  } catch (err) {
    console.error('表单校验失败:', err);
  } finally {
    loading.value = false;
  }
};
/** 列设置 */
const tableColumns = [
  // 新增：选择列
  {
    prop: 'selection',
    label: '选择',
    width: 60,
    type: 'selection',
    fixed: 'left'
  },
  { prop: 'mealUnit', label: '配餐单位', width: 180 },
  { prop: 'airlineComp', label: '航空公司', width: 120 },
  { prop: 'flightNo', label: '航班号', width: 120 },
  { prop: 'aircraftType', label: '机型', width: 120 },
  { prop: 'schPat', label: '班期', width: 100 },
  { prop: 'depLoc', label: '起飞地点', width: 120 },
  { prop: 'depIata', label: '三字代码', width: 120 },
  { prop: 'carType', label: '车型', width: 120 },
  { prop: 'inboundTime', label: '进港时间', width: 120 },
  { prop: 'returnTime', label: '返港时间', width: 120 },
  { prop: 'depTime', label: '起飞时间', width: 120 },
  { prop: 'arrLoc', label: '降落地点', width: 100 },
  { prop: 'arrIata', label: '三字代码', width: 120 },
  { prop: 'arrTime', label: '降落时间', width: 120 },
  { prop: 'flyDur', label: '公布飞行时长', width: 120 },
  { prop: 'avgActualDur', label: '平均飞行时长', width: 120 },
  { prop: 'flightType', label: '航班性质', width: 120 },
  { prop: 'airlinePattern', label: '航班类型', width: 120 },
  { prop: 'bussClassMeal', label: '商务舱', width: 180 },
  { prop: 'premEcoClassMeal', label: '高级经济舱', width: 180 },
  { prop: 'ecoClassMeal', label: '经济舱', width: 180 },
  { prop: 'crewMeal', label: '机组', width: 180 },
  { prop: 'weeklyMealQty', label: '周配餐量', width: 120 },
  { prop: 'company', label: '所属公司', width: 150 },
  { prop: 'companyIata', label: '所属公司三字代码', width: 150 },
  { prop: 'airlineType', label: '航线类别', width: 180 },
  { prop: 'effectiveDate', label: '执行日期', width: 240 },
  { prop: 'remarks', label: '备注', width: 120 },
  { prop: 'isWaterPkg', label: '小水放袋/盒', width: 120 },
  { prop: 'isConnFlight', label: '联程航班', width: 120 },
  { prop: 'cateringSite', label: '航食站点', width: 120 },
  { prop: 'nonStd', label: '非标', width: 120 },
  { prop: 'isMatche', label: '匹配', width: 180 },
  { prop: 'flightCount', label: '航班量统计', width: 120 },
  { prop: 'createTime', label: '创建时间', width: 180 }
]

const columnVisibility = ref<Record<string, boolean>>({})
const selectedColumns = ref<string[]>([])
const columnSettingVisible = ref(false)

const initColumnVisibility = () => {
  const visibility: Record<string, boolean> = {}
  const selected: string[] = []

  tableColumns.forEach((column) => {
    visibility[column.prop] = true
    selected.push(column.prop)
  })

  columnVisibility.value = visibility
  selectedColumns.value = selected
}

const openColumnSetting = () => {
  columnSettingVisible.value = true
}

const saveColumnSettings = () => {
  const newVisibility: Record<string, boolean> = {}
  tableColumns.forEach((column) => {
    newVisibility[column.prop] = false
  })
  selectedColumns.value.forEach((prop) => {
    newVisibility[prop] = true
  })
  columnVisibility.value = newVisibility
  columnSettingVisible.value = false
}

/** 核心：虚拟化表格列配置 - 修复问题 */
const tableV2Columns = computed<Column<QuarterPlanVO>[]>(() => {
  // 1. 序号列：修复NaN问题，使用数据索引计算
  const indexColumn: Column<QuarterPlanVO> = {
    key: 'index',
    title: '序号',
    width: 80,
    cellRenderer: ({ rowData }) => {
      // 通过数据在数组中的位置计算序号
      const index = list.value.findIndex(item => item.id === rowData.id)
      return <span class="flex items-center justify-center">{index > -1 ? index + 1 : ''}</span>
    }
  }

  // 2. 动态列：修复创建时间和备注问题
  const dynamicColumns = tableColumns
    .filter(column => columnVisibility.value[column.prop])
    .map(column => ({
      key: column.prop,
      title: column.label,
      dataKey: column.prop,
      width: column.width || 120,
      fixed: column.fixed,
      cellRenderer: ({ cellData, rowData }) => {
        const row = rowData as QuarterPlanVO
        const value = cellData?.toString() || ''

        // 新增：选择列渲染
        if (column.prop === 'selection') {
          return (
            <ElCheckbox
              modelValue={selectedRowKeys.value.includes(row.id as number)}
              onUpdate:modelValue={() => handleSelect(row.id as number)}
              class="flex items-center justify-center"
            />
          )
        }

        // 特殊列：航线类型
        if (column.prop === 'airlinePattern') {
          return h(DictTag, {
            type: DICT_TYPE.PPLAN_AIRLINE_TYPE,
            value: row.airlinePattern
          })
        }

        // 特殊列：航线类别
        if (column.prop === 'airlineType') {
          return h(DictTag, {
            type: DICT_TYPE.PPLAN_AIRLINE_TYPE_1,
            value: row.airlineType
          })
        }

        // 特殊列：航空公司
        if (column.prop === 'airlineComp') {
          return h(DictTag, {
            type: DICT_TYPE.PPLAN_AIRLINE_ID,
            value: row.airlineComp
          })
        }

        // 特殊列：创建时间（修复不回显问题）
        if (column.prop === 'createTime') {
          // 确保日期格式化函数能处理各种时间格式
          const formattedTime = row.createTime 
            ? formatDate(row.createTime) 
            : '-'
          return <span class="flex items-center justify-center">{formattedTime}</span>
        }

        // 特殊列：备注（修复换行问题，添加tooltip）
        if (column.prop === 'remarks') {
          return (
            <ElTooltip content={value || '-'} placement="top">
              <div class="overflow-hidden whitespace-nowrap text-ellipsis w-full ">
                {value || '-'}
              </div>
            </ElTooltip>
          )
        }

        // 普通列
        return <span class="flex items-center justify-center">{value || '-'}</span>
      },
      // 新增：选择列表头渲染
      headerRenderer: () => {
        if (column.prop === 'selection') {
          return (
            <ElCheckbox
              modelValue={isAllSelected.value}
              onUpdate:modelValue={handleSelectAll}
              class="flex items-center justify-center"
            />
          )
        }
        return <span class="flex items-center justify-center">{column.label}</span>
      }
    }))

  // 3. 操作列
  const actionColumn: Column<QuarterPlanVO> = {
    key: 'operations',
    title: '操作',
    width: 120,
    fixed: 'right',
    cellRenderer: ({ rowData }) => {
      const row = rowData as QuarterPlanVO
      return (
        <div style="display: flex; align-items: center; justify-content: center; gap: 8px;">
          <ElButton
            type="primary"
            link
            size="small"
            onClick={() => openForm('update', row.id)}
          >
            编辑
          </ElButton>
          <ElButton
            type="danger"
            link
            size="small"
            onClick={() => handleDelete(row.id)}
          >
            删除
          </ElButton>
        </div>
      )
    }
  }

  return [indexColumn, ...dynamicColumns, actionColumn]
})

/** 初始化 */
onMounted(() => {
  initColumnVisibility()
  getList()
})

watch(selectedColumns, () => {}, { deep: true })

// 监听列表变化，同步选择状态
watch(list, () => {
  selectedRowKeys.value = []
}, { deep: true })
</script>

<style scoped>
.column-setting-group {
  max-height: 300px;
  overflow-y: auto;
  padding-right: 10px;
}

:deep(.column-setting-group .el-checkbox) {
  display: block;
  margin-bottom: 10px;
}

/* 虚拟化表格样式 */
:deep(.el-table-v2__cell) {
  padding: 4px 8px !important;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-table-v2__header) {
  background-color: #f8fafc !important;
  border-bottom: 1px solid #e6e6e6;
}

:deep(.el-table-v2__header-cell) {
  font-weight: 500;
  color: #333;
}

:deep(.el-button--text) {
  padding: 0 4px;
}

/* 修复备注列样式 */
.overflow-hidden {
  overflow: hidden;
}

.whitespace-nowrap {
  white-space: nowrap;
}

.text-ellipsis {
  text-overflow: ellipsis;
}

.text-center {
  text-align: center;
}

/* 新增：批量操作弹窗样式 */
.batch-operation-content {
  padding: 10px 0;
}
.batch-operation-content p {
  margin-bottom: 15px;
  color: #666;
}
.text-primary {
  color: #409eff;
  font-weight: 500;
}
</style>